﻿// HTTPIN_Alarm V0.008
// Receives alarms from the web database and informs users. The list of people who get the alarm wil be build from the notecard titles in the inventory of the object. Please name with the key of the users to receive an alarm

integer g_iTimeOut = 1790; // time between alarms

string g_sSERVER = "http://collardata1.appspot.com";
string g_sBROADCAST_URL = "/alarm/urlset";
string g_sDATA_AVSYNC_URL = "/avsync/setname";
//string g_sCMDS_AVSYNC_URL = "http://collarcmds1.appspot.com/avsync/setkey";
key g_kNewUrlRequest;
key g_kBroadcastRequest;
key g_kBroadcastRequestDel;
string g_sCurrentUrl = "";

list g_kAdminKeys;

integer g_iPubEnabled = 0;//anyone can control in SL

key g_kWearer;

integer g_iEnabled = 1;

integer g_iNoAlarm=FALSE;

list g_lNameReqID;

Debug(string sStr)
{
    llOwnerSay(sStr);
}

Notify(key kID, string sMsg, integer iAlsoNotifyWearer)
{
    if (kID == g_kWearer)
    {
        llOwnerSay(sMsg);
    }
    else
    {
        llInstantMessage(kID, sMsg);
        if (iAlsoNotifyWearer)
        {
            llOwnerSay(sMsg);
        }
    }
}

NewURL()
{
    if(llGetFreeURLs() == 0)
    {
        Debug("Unable to generate new url because there are not enough free urls");
        return;
    }
    llSay(0, "Requesting new url. Remaining urls: " + (string)llGetFreeURLs());
    g_kNewUrlRequest = llRequestURL();

}

ClearURL()
{
    if(g_sCurrentUrl != "")
    {
        llSay (0, "Released access url");
        llReleaseURL(g_sCurrentUrl);
    }
    Debug("Deleting access url");
    g_sCurrentUrl = "";
}

AddAdmins()
{
    integer i;
    integer iCount = llGetInventoryNumber(INVENTORY_NOTECARD);
    string sName;

    g_kAdminKeys = [];

    for (i = 0; i < iCount; i++)
    {
        sName = llGetInventoryName(INVENTORY_NOTECARD, i);
        if (llStringLength(sName) == 36)
        {
            g_kAdminKeys += [(key)sName];
            llSay(0, "Admin key added: " + sName);
        }
    }
}

default
{
    state_entry()
    {
        if ((llGetObjectDesc()!="(No Description)")  && (llGetObjectDesc()!=""))
        {
            g_sSERVER = llGetObjectDesc();
        }

        Debug("State Entry!");
        g_sCurrentUrl = "";
        g_kWearer = llGetOwner();
        AddAdmins();
        llSay(0, "OpenCollar HTTPIN alarm is now initialzed.\nServer: " + g_sSERVER + "\nAdmins can click it to submit the URL to the DB.");
        llSetText(llGetObjectName()+"\nServer:\n"+g_sSERVER,<1,1,1>,1);
    }

    on_rez(integer n)
    {
        Debug("On Rez!");
        g_sCurrentUrl = "";
        llResetScript();
    }

    changed(integer c)
    {
        if (c & (CHANGED_REGION | CHANGED_REGION_START | CHANGED_TELEPORT) )
        {
            Debug("Changed Event!");
            g_sCurrentUrl = "";
            NewURL();
        }
        else if (c & CHANGED_INVENTORY)
        {
            llResetScript();
        }
    }

    touch_start(integer num_detected)
    {
        g_iNoAlarm=FALSE;
        Debug(g_sCurrentUrl);
        key kToucher = llDetectedKey(0);
        if ((kToucher == g_kWearer) || (llListFindList(g_kAdminKeys,[kToucher])))
        {
            AddAdmins();
            if (g_sCurrentUrl != "");
        {
            ClearURL();
        }
            NewURL();
        }
    }

    http_request(key kID, string sMethod, string sBody)
    {
        if ((sMethod == URL_REQUEST_GRANTED) && (kID == g_kNewUrlRequest) )
        {
            g_sCurrentUrl = sBody;
            g_kNewUrlRequest = NULL_KEY;
            Debug("Obtained URL: " + g_sCurrentUrl);
            llSay(0, "URL received.");
            g_kBroadcastRequest = llHTTPRequest(g_sSERVER + g_sBROADCAST_URL, [HTTP_METHOD, "POST"], g_sCurrentUrl);
        }
        else if ((sMethod == URL_REQUEST_DENIED) && (kID == g_kNewUrlRequest))
        {
            llSay(0, "There was a problem, and an URL was not assigned: " + sBody);
            g_kNewUrlRequest = NULL_KEY;
        }
        else if (g_sCurrentUrl == "")
        {
            Debug("Got Command While Offline: " + sBody);
            llHTTPResponse(kID,403,"Forbidden");
        }
        else if (sMethod == "POST")
        {
            string sPath = llGetHTTPHeader(kID, "x-path-info");
            llHTTPResponse(kID,200,"Alarm Received");

            Debug("HTTP-Request (" + sMethod + ") URL: '"+ sPath +"'; Body " + sBody);

            if (sPath == "/Key2Name/")
            {
                Debug ("Key2Name request: " + sBody);
                key kReqID = llRequestAgentData(sBody,DATA_NAME);
                g_lNameReqID += [kReqID, sBody];
            }
            else
            {
                // alarm stuff
                if (!g_iNoAlarm)
                {
                    g_iNoAlarm = TRUE;
                    llSetTimerEvent(g_iTimeOut);

                    integer i;
                    integer iCount = llGetListLength(g_kAdminKeys);
                    string sName;

                    for (i = 0; i < iCount; i++)
                    {
                        llInstantMessage(llList2Key(g_kAdminKeys, i), "Alarm from OpenCollar Database:\n" + sBody);
                    }
                }
            }

        }
    }

    http_response(key kRquestID, integer iStatus, list lMetadata, string sBody)
    {
        if(kRquestID == g_kBroadcastRequest)
        {
            if(iStatus != 200 && sBody != "Added")
                ClearURL();
            Debug("Got response from add lookup: (" + (string)iStatus + ") " + sBody);
        }
        else if(kRquestID == g_kBroadcastRequestDel)
        {
            Debug("Got response from del lookup: (" + (string)iStatus + ") " + sBody);
        }
        else
        {
            Debug("Got unknown response: (" + (string)iStatus + ") " + sBody);
        }
    }

    timer()
    {
        llSetTimerEvent(0);
        g_iNoAlarm = FALSE;
    }


    dataserver( key kQuery, string sData)
    {
        integer iInList= llListFindList(g_lNameReqID, [kQuery]);
        if (iInList >= 0)
        {
            string sPersonkey = llList2String(g_lNameReqID, iInList + 1);
            llDeleteSubList(g_lNameReqID, iInList, iInList + 1);
            Debug("The key '"+sPersonkey+"' belongs to '"+sData+"'! Sending to apps now: " + g_sSERVER + g_sDATA_AVSYNC_URL);
            llHTTPRequest(g_sSERVER + g_sDATA_AVSYNC_URL, [HTTP_METHOD, "POST"], "name=" + sData + "\nkey=" + sPersonkey);
        }
    }

}
